<template>
  <div class="project">
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="relative mb16 filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :is-show-filter="isShowFilter"
          :filter-list="filterList"
          :default-select-key="defaultSelectKey"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <div class="current-user-action-box">
          <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick" >我发起的</el-checkbox>
          <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
          <el-checkbox v-model="isMyPending" @change="queryClick" >待我处理</el-checkbox>
        </div>
        <createBtn v-if="hasRouteAuth('crm:arrearsTransfer:create') || isAdmin" style="margin-right: 10px;" text="转交欠款" @click.native="toCreate"/>
        <MoreOpeator ref="moreOpeatorRef" :list="moreOperatorList" />
      </div>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length"
          ref="arrearsTransferRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
            <template slot-scope="scope" slot="header">
              <div class="diyHeader">{{ scope.column.label }}</div>
            </template>
            <template slot-scope="scope">
              <processSn :is-expedited="scope.row.isExpedited">
                <div class="light-word" @click="toDetail(scope.row)">
                  <ToolTip :content="handleSnNumber(scope.row.approvalNo)" is-can-click @handelClick="toDetail(scope.row)"/>
                </div>
              </processSn>
            </template>
          </u-table-column>
          <u-table-column align="left" label="转交人" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.passer" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="转交欠款(元)" width="130" sortable prop="amount">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="被转交人" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.transferee" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="转交说明" width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="当前节点">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.currentNode" />
            </template>
          </u-table-column>
          <u-table-column :min-width="handleTdWidth(120,150)" align="left" label="当前处理人">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.currentHandler" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态" width="100">
            <template slot-scope="scope">
              <StatusText
                v-if="scope.row.status || scope.row.status===0"
                :color="['#406eff','#fd8546', 'red', '#999', '#31cc9c','#406eff'][scope.row.status]"
                :text="scope.row.status | energyStatus" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.department" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" width="160" sortable prop="createTime">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">{{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" :fixed="operateFix" align="left" label="操作">
            <template slot-scope="scope">
              <div class="flex-center">
                <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                <MoreOpeator
                  :list="[
                    {
                      label: '查看',
                      handelClick: () => {toDetail(scope.row)},
                      auth: scope.row.status !== 0 && showMobilePage
                    },{
                      label: '复制',
                      handelClick: () => {handlerCreateNew(scope.row)},
                      disabled: scope.row.status === 0 || !hasRouteAuth('crm:arrearsTransfer:create')
                    },{
                      label: '编辑',
                      handelClick: () => {handleEdit(scope.row)},
                      disabled: setEditDisable(scope.row)
                    },{
                      label: '删除',
                      handelClick: () => {handleDelete(scope.row)},
                      disabled: setDelDisable(scope.row)
                    }
                  ]"
                >
                  <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                </MoreOpeator>
              </div>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit"/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :is-show-filter="isShowFilter"
            :filter-list="filterList"
            :default-select-key="defaultSelectKey"
            show-mobile-icon
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus">
            <div slot="checkGroup">
              <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick" >我发起的</el-checkbox>
              <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
              <el-checkbox v-model="isMyPending" @change="queryClick" >待我处理</el-checkbox>
            </div>
          </FilterInput>
          <MoreOpeator ref="moreOpeatorRef" :list="moreOperatorList" show-mobile-icon />
          <createBtn v-if="hasRouteAuth('crm:arrearsTransfer:create') || isAdmin" mobile-table text="转交欠款" @click.native="toCreate"/>
        </template>
        <template v-else>
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <div style="flex: 1;" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
    <ApproverChange
      ref="approverChangeDialog"
      :business-type="BUSINESS_TYPE.ARREARS_TRANSFER"
      :ids="curSelectedId"
      @changeCallBack="changeCallBack"/>
    <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
  </div>
</template>

<script>
// api
import { deleteArrearsTransfer, getArrearsTransferList, getArrearsTransferTab } from '@/api/arrearsTransfer';
import { getDepartmentAll } from '@/api/config';
import ListTab from '@/components/ListTab';
import createButton from '@/components/CreateButton';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { standardFormat } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import { CURRENT_NODE_MODULE } from '@/utils/const';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import isAdmin from '@/mixins/isAdmin';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { energyStatus } from '@/filters/status';
import { PROCESS_TYPE } from '@/utils/const/process';
import { commonOptions } from '@/utils/tools';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import approverChange from '@/mixins/approverChange';
import { expeditedOptions } from '@/filters/status';

export default {
  components: {
    ListTab,
    createButton,
    EmptyPlaceholder,
    MoreOpeator,
    createBtn,
    DiversAuditorDialog
  },
  filters: { standardFormat, energyStatus },
  mixins: [
    tableSelections,
    isAdmin,
    TableAdaptive,
    mobileTable,
    filterObjStoreMixin,
    copyLink,
    schedule,
    approverChange
  ],
  data() {
    return {
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      isUmyTable: true,
      tabList: [],
      activeId: -1,
      listLoading: false,
      page: 1,
      perPage: 20,
      sortName: '',
      sortType: '',
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      paramsObj: {},
      departmentOption: [],
      isShowFilter: false,
      defaultSelectKey: '',
      tableRefName: 'arrearsTransferRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    rangeKeyArr() {
      return [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'amount',
        start: 'amountStart',
        end: 'amountEnd',
        type: 'moneyFixed'
      }];
    },
    arrayKeyArr() {
      return ['departmentIds', 'currentNode'];
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'approvalNo', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'passer', name: '转交人', labelWidth: '100px', type: 'input' },
        { keyword: 'transferee', name: '被转交人', labelWidth: '100px', type: 'input' },
        { keyword: 'remark', name: '转交说明', labelWidth: '100px', type: 'input' },
        { keyword: 'currentHandler', name: '当前处理人', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '100px', type: 'input' },
        {
          keyword: 'amount', name: '转交欠款', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        },
        // 下拉
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        {
          keyword: 'departmentIds',
          name: '所属部门',
          type: 'cascaderSelectWithChild',
          childrenVal: 'children',
          options: this.departmentOption
        },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.ARREARS_TRANSFER },
          labelName: 'name',
          placeholder: '当前节点',
          searchkeyword: 'keyword',
          apiUrl: 'admin/common/currentNodes'
        },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 196 : 188;
    },
    moreOperatorList() {
      return [
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink },
        { label: '批量转交', handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.ARREARS_TRANSFER) }
      ];
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'arrearsTransferDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      this.isShowFilter = false;
      this.activeId = this.$route.query.tabStatus !== undefined ? Number(this.$route.query.tabStatus) : -1;
      if (this.$route.query.proposer) {
        const { proposer, transferType } = this.$route.query;
        const transferKey = transferType === '0' ? 'passer' : 'transferee';
        this.$set(this.paramsObj, transferKey, proposer);
        this.$set(this.paramsObj, 'status', 4);
        this.defaultSelectKey = transferKey;
      }
      this.fetchData(true);
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  methods: {
    hasRouteAuth,
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}#/businessPage/arrearsTransferDetail?id=${item.id}&processId=${item.processId}`;
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.departmentOption = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    toCreate() {
      this.$router.push({ name: 'arrearsTransferCreate' });
    },
    formatParams(sendPageConfig = true) {
      const { page, perPage, activeId, paramsObj, activeName, sortName, sortType } = this;
      const params = JSON.parse(JSON.stringify(paramsObj));
      // 设置tab
      if (activeName !== '全部') params.tabStatus = activeId;
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      params.sortName = sortName || '';
      params.sortType = sortType || '';
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.getTabList(params);
      this.listLoading = true;
      getArrearsTransferList(params).then(({ data = {}} = {}) => {
        this.list = data;
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    // 获取顶部Tab列表（成本状态）
    async getTabList(params = {}) {
      try {
        const result = await getArrearsTransferTab(params);
        const { code, data = [] } = result;
        if (code === 200) {
          this.tabList = data;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 },
          { id: 0, name: '待提交', num: 0 },
          { id: 1, name: '审批中', num: 0 },
          { id: 2, name: '已完成', num: 0 },
          { id: 3, name: '已作废', num: 0 }
        ];
        console.log(error);
      }
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、已撤销、未过审、待提交
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.hasRouteAuth('crm:arrearsTransfer:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    handleTabClick(id) {
      this.activeId = id;
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toDetail(item) {
      this.filterObjStore(PROCESS_TYPE.ARREARS_TRANSFER);
      this.$router.push({
        name: 'arrearsTransferDetail',
        query: {
          id: item.id,
          processId: item.processId,
          fromList: 1
        }
      });
    },
    handleEdit(row) {
      this.$router.push({
        name: 'arrearsTransferEdit',
        params: { id: row.id }
      });
    },
    handleDelete(row) {
      showModal('确定删除该转交欠款单?').then(() => {
        deleteArrearsTransfer(row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(row.id);
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    handlerCreateNew(row) {
      const routeUrl = this.$router.resolve({
        name: 'arrearsTransferEdit',
        params: { id: row.id },
        query: { reapplyId: row.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.dot-wrap {
  @extend %dot-wrap;
}
$bgc: #FFBC3D 0, #FD8546 1, #FF4E5F 2, #999 3, #31CC9C 4, #406EFF 5;
.project {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .filter{
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      position: relative;
      .current-user-action-box {
        position: absolute;
        left: 488px;
        top: 6px;
        display:flex;
        align-items:center;
      }
    }
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
    .dot {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      margin-right: 5px;
      @each $c, $i in $bgc {
        &.color-#{$i} {
          background: $c;
        }
      }
    }
  }
}
.dropdown-wrap {
  margin-top: -24px;
  margin-right: 15px;
  padding: 0;
  .el-dropdown-menu__item {
    width: 90px;
    text-align: center;
  }
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
